from flask import Flask, redirect, url_for, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bootstrap import Bootstrap5
from flask_pymongo import PyMongo
from flask_mail import Mail
from .config import Config

db = SQLAlchemy()
mongo = PyMongo()
login_manager = LoginManager()
bootstrap = Bootstrap5()
mail = Mail()


def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    db.init_app(app)
    login_manager.init_app(app)
    bootstrap.init_app(app)
    mongo.init_app(app)
    mail.init_app(app)

    login_manager.login_view = 'user.login'
    login_manager.login_message = '请先登录'

    # 添加根路由重定向
    @app.route('/')
    def index():
        return redirect(url_for('user.index'))

    from .user import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/user')

    from .admin import bp as admin_bp
    app.register_blueprint(admin_bp, url_prefix='/admin')

    @app.errorhandler(404)
    def page_not_found():
        return render_template('error_404.html',
                               error_code=404,
                               error_title='页面未找到',
                               error_message='抱歉，您访问的页面不存在',
                               title='404'), 404

    return app


from app.models import User


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
